package com.csj.mvvmtest.ui.fourth

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.csj.mvvm.algorithm.ASCIIUtil
import com.csj.mvvm.api.HttpUtil
import com.csj.mvvm.api.HttpUtil2
import com.csj.mvvm.api.URLConstant
import com.csj.mvvm.api.error.ErrorUtil
import com.csj.mvvm.api.interceptor.BearInterceptor
import com.csj.mvvm.bean.HttpResponse
import com.csj.mvvm.ui.base.BaseViewModel
import com.csj.mvvm.utils.LogUtil
import com.csj.mvvmtest.bean.FourthBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import java.util.*

class FourthModel : BaseViewModel() {

    val appid = "ab2023082501"
    val secret = "z06ms96daa4x1286pmz647ckvsoxikcq"

    override var httpUtil: HttpUtil = HttpUtil2.getInstance()

    var tokenData = MutableLiveData<FourthBean>()
    var hotsData = MutableLiveData<FourthBean>()

    fun getToken() {
        BearInterceptor.access_token = ""
        val has = mutableMapOf("app_id" to appid)
        post2("api/user/author", has, tokenData, false)
    }

    fun getHots() {
        val map = TreeMap<String, String>()
        map["timestamp"] = System.currentTimeMillis().toString().substring(0, 10)
        map["lang"] = "zh_CN"
        map["pageSize"] = "2"
        post3("api/music/musicHots", map, hotsData, false)
    }

    inline fun <reified M : HttpResponse> launch2(
        noinline block: suspend CoroutineScope.() -> ResponseBody,//请求接口方法，M表示data实体泛型，调用时可将data对应的bean传入即可
        liveData: MutableLiveData<M>,
        isShowLoading: Boolean = true,
        isShowError: Boolean = true,
        index: Int = apiIndex
    ) {
        if (isShowLoading) showLoading()
        viewModelScope.launch {
            try {
//                val result1 = withContext(Dispatchers.IO) { block() }
//                LogUtil.e("请求result>>${result1.string()}")
                val result = withContext(Dispatchers.IO) {
                    httpUtil.getConverter().converter(block(), M::class.java)
                }
                LogUtil.e("请求result>>$result")
                liveData.value = result
            } catch (e: Throwable) {//接口请求失败
                LogUtil.e("请求异常>>" + e.message)
                val errorResult = ErrorUtil.getError(e)
                errorResult.show = isShowError
                errorResult.index = index
                showError(errorResult)
            } finally {//请求结束
                dismissLoading()
            }
        }
    }

    inline fun <reified M : HttpResponse> post2(
        path: String,
        params: Map<String, String?> = HashMap(),
        liveData: MutableLiveData<M> = MutableLiveData(),
        isShowLoading: Boolean = true,
        isShowError: Boolean = true
    ) {
        val formBody: RequestBody =
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSONObject(params).toString()
            )
        launch2({
            httpUtil.getService().json(path, formBody)
        }, liveData, isShowLoading, isShowError)
    }

    inline fun <reified M : HttpResponse> post3(
        path: String,
        map: TreeMap<String, String> = TreeMap(),
        liveData: MutableLiveData<M> = MutableLiveData(),
        isShowLoading: Boolean = true,
        isShowError: Boolean = true
    ) {
        val js = JSONObject()
        try {
            for (key in map.keys) {
                js.put(key, map[key])
            }
            js.put("sign", ASCIIUtil.getDigestByMD5(map, URLConstant.BASE_URL2 + path, secret))
        } catch (e: Exception) {
        }
        val formBody =
            RequestBody.create(MediaType.parse("application/json; charset=utf-8"), js.toString())
        launch2({
            httpUtil.getService().json(path, formBody)
        }, liveData, isShowLoading, isShowError)
    }
}